package com.unidt.www.module.third.workbar.api;

import com.unidt.www.module.third.api.workbar.IWorkMessageApi;
import com.unidt.www.module.third.api.workbar.dto.MessageBody;
import com.unidt.www.module.third.workbar.app.WorkBarUtils;
import com.unidt.www.module.third.workbar.dao.WorkMessageMapper;
import com.unidt.www.module.third.workbar.domain.TWorkMessageDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author sk
 * @Description:
 * @Date 2022/12/9 23:29
 **/
@Service
public class WorkMessageApiImpl implements IWorkMessageApi {
    @Autowired
    WorkBarUtils workBarUtils;

    @Autowired
    WorkMessageMapper workMessageMapper;

    @Override
    public void sendMessage(MessageBody messageBody, String taskId) {

        List<String> receiverIds  =  messageBody.getReceiverIds();
        receiverIds.forEach(m->{
            TWorkMessageDo tWorkMessageDo = new TWorkMessageDo();
            tWorkMessageDo.setContent(messageBody.getContent());
            tWorkMessageDo.setZzdCode(m);
            tWorkMessageDo.setTitle(messageBody.getTitle());
            tWorkMessageDo.setTaskId(taskId);
            tWorkMessageDo.setCreateTime(LocalDateTime.now());
            tWorkMessageDo.setStatus(0);
            this.workMessageMapper.insert(tWorkMessageDo);
            List<String> r = new ArrayList<>();
            r.add(m);
            messageBody.setNotifyId(String.valueOf(tWorkMessageDo.getId()));
            messageBody.setReceiverIds(r);
            this.workBarUtils.sendMessage(messageBody);

        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void endMessage(String zzdCode, String taskId) {
        List<TWorkMessageDo> list = this.workMessageMapper.getMessageList(zzdCode,taskId);
        if(!list.isEmpty()){
            list.forEach(m->{
                this.workBarUtils.endMessage(String.valueOf(m.getId()));
                m.setEndTime(LocalDateTime.now());
                m.setStatus(1);
                this.workMessageMapper.updateById(m);
            });
        }

    }


}
